<?php 
/****

	If you want the best of the world,
give the world your best anytime！
            				——不二
                							
****/

//defined('ACCESS')||exit('Forbidden!');

//验证码类
class Captcha{

	//生成随机字符串
	private static function randStr($len = 4){
		$str = str_shuffle('23456789abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ');
		return substr($str, 0 , $len);
	}


	//创建缩略图
	public static function thumb($ori,$width=300,$height=300){
		//创建小画布
		$pic = imagecreatetruecolor($width, $height);
		$pink = imagecolorallocate($pic, 200, 100, 100);
		imagefill($pic, 0, 0, $pink);
		//获取原图
		$map = array(
			1=>'imagecreatefromgif',
			2=>'imagecreatefromjpeg',
			3=>'imagecreatefrompng',
			15=>'imagecreatefromwbmp'
			);
		$opath = ROOT . $ori;
		list($w,$h,$type) = getimagesize($opath);
		if (!isset($map[$type])) {
			return false;
		}
		//$opath = dirname($ori);
		$opic = $map[$type]($opath);
		$rate = min($width/$w,$height/$h);
		$faw = $w*$rate;
		$fah = $h*$rate;
		//imagecopyresampled(dst_image, src_image, dst_x, dst_y, src_x, src_y, dst_w, dst_h, src_w, src_h)
		imagecopyresampled($pic, $opic, ($width-$faw)/2, ($height-$fah)/2, 0, 0, $faw, $fah, $w, $h);


		$opath = dirname($ori);
		$path = $opath.'/'.self::randStr() . '.png';
		$fpath = ROOT.$path;

		imagepng($pic,$fpath);

		imagedestroy($pic);
		imagedestroy($opic);

		return $path;
	}

	//添加水印
	public static function water($ori,$water){
		$fori = ROOT.$ori;
		$path = dirname($ori).'/'.self::randStr().'.png';
		$fpath = ROOT.$path;
		list($ow,$oh,$otype) = getimagesize($fori);
		list($ww,$wh,$wtype) = getimagesize($water);
		$map = array(
			1=>'imagecreatefromgif',
			2=>'imagecreatefromjpeg',
			3=>'imagecreatefrompng',
			15=>'imagecreatefromwbmp'
			);
		if ((!isset($map[$otype])) || (!isset($map[$wtype]))) {
			return false;
		}
		$opic = $map[$otype]($fori);
		$wpic = $map[$wtype]($water);
		imagecopymerge($opic, $wpic, ($ow-$ww), ($oh-$wh), 0, 0, $ww, $wh, 50);
		imagepng($opic,$fpath);

		imagedestroy($opic);
		imagedestroy($wpic);
		return $path;
	}

	//生成验证码
	public static function yanZhengMa($num=4){
		$pic = imagecreatetruecolor(60, 30);
		$red = imagecolorallocate($pic, 255, 0, 0);
		$str = self::randStr($num);
		//imagestring(image, font, x, y, string, color)
		imagestring($pic, 5, 10, 6, $str, $red);
		header('content-type:image/png');
		imagepng($pic);

		imagedestroy($pic);
		//return $str;
		//setcookie('yanzheng',$str);
		//session_start();
		$_SESSION['yanzheng'] = $str;
	}

	//检测验证码
	public static function checkCaptcha($captcha){
		return $captcha === strtolower($_SESSION['yanzheng']);
	}
}

//Captcha::yanZhengMa(4);

?>